#!/bin/bash

# DEBUGGING CONTROLS
# set -x
# trap read debug


#### Functions

tidy_item()
{
	local trimmed1="$(echo -e "$1" | sed -e 's/[[:blank:]\",]*$//')" #Remove whitespace, the quote and comma at the end of each line
	local trimmed2="$(echo -e "$trimmed1" | sed -e 's/^[[:blank:]\"]*//')" # Remove whitespace and quote at the start of the line
	echo "$trimmed2"
}


#### Main

force_rebuild=false
exclude_file="/Library/Application Support/UrBackup Client/var/urbackup/macos_exclusions.txt"


# Check if rebuild has been forced
if [ "$1" != "" ]; then
	if [[ "$1" == "-f" ]] || [[ "$1" == "--force" ]]; then
		force_rebuild=true
	fi
fi


# Check macos_exclusion file doesn't already exist
if [ -f "$exclude_file" ]; then
	if !($force_rebuild); then
		exit 0
	else
		rm "$exclude_file"
	fi
fi


paths_excluded=$(defaults read "/System/Library/CoreServices/backupd.bundle/Contents/Resources/StdExclusions.plist" PathsExcluded)
contents_excluded=$(defaults read "/System/Library/CoreServices/backupd.bundle/Contents/Resources/StdExclusions.plist" ContentsExcluded)
file_contents_excluded=$(defaults read "/System/Library/CoreServices/backupd.bundle/Contents/Resources/StdExclusions.plist" FileContentsExcluded)
user_paths_excluded=$(defaults read "/System/Library/CoreServices/backupd.bundle/Contents/Resources/StdExclusions.plist" UserPathsExcluded)


paths_excluded_array=()

IFS=$'\n'
for item in $paths_excluded; do
	if [[ "$item" != "(" ]] && [[ "$item" != ")" ]]; then # Remove the leading and trailing paratheses
		tidied="$(echo -e $(tidy_item $item))"
		paths_excluded_array+=("$tidied")
	fi
done

for item in $contents_excluded; do
	if [[ "$item" != "(" ]] && [[ "$item" != ")" ]]; then # Remove the leading and trailing paratheses
		tidied="$(echo -e $(tidy_item $item))"
		paths_excluded_array+=("$tidied/*")
	fi
done

# Need to refine this
for item in $file_contents_excluded; do
	if [[ "$item" != "(" ]] && [[ "$item" != ")" ]]; then # Remove the leading and trailing paratheses
		tidied="$(echo -e $(tidy_item $item))"
		paths_excluded_array+=("$tidied/*")
	fi
done

for item in $user_paths_excluded; do
	if [[ "$item" != "(" ]] && [[ "$item" != ")" ]]; then # Remove the leading and trailing paratheses
		tidied="$(echo -e $(tidy_item $item))"
		paths_excluded_array+=("/Users/*/$tidied")
	fi
done

# Hardcode paths for DataVaults

paths_excluded_array+=("/Users/*/Library/VoiceTrigger/SAT")
paths_excluded_array+=("/Users/*/Library/Containers/com.apple.mail/Data/DataVaults")
paths_excluded_array+=("/var/folders/*/*/*/com.apple.nsurlsessiond")


set -f
sorted_array=($(sort <<<"${paths_excluded_array[*]}"))

mkdir -p "/Library/Application Support/UrBackup Client/var/urbackup"
touch $exclude_file

for i in "${sorted_array[@]}"; do
	echo "$i" >> $exclude_file
done

exit 0